import numpy as np
from scipy.fftpack import dct
import librosa
import matplotlib.pyplot as plt
from scipy import signal

filepath = r"C:\Users\Administrator\Desktop\heart_sound\four_audios\AS_New\New_AS_001.wav"
signals, sr = librosa.load(path=filepath, sr=16000)

# 预加重
pre_emphasis = 0.97
# emphasized_signal = np.append(signals[0], signals[1:] - pre_emphasis * signals[:-1])
emphasized_signal = signal.lfilter([1, -pre_emphasis], [1], signal)
# 分帧
frame_size = 0.025
frame_stride = 0.01
frame_length, frame_step = frame_size * sr, frame_stride * sr  # 转换为采样点数
signal_length = len(emphasized_signal)
frame_length = int(round(frame_length))
frame_step = int(round(frame_step))
num_frames = int(np.ceil(float(np.abs(signal_length - frame_length)) / frame_step))
pad_signal_length = num_frames * frame_step + frame_length
z = np.zeros((pad_signal_length - signal_length))
pad_signal = np.append(emphasized_signal, z)  # 填充信号以确保所有帧具有相同数量的采样点

# 加窗
frames = np.array([pad_signal[i:i + frame_length] for i in range(0, pad_signal_length - frame_length + frame_step, frame_step)])
frames *= np.hamming(frame_length)

# 离散傅里叶变换（DFT）
N_FFT = 512
mag_frames = np.absolute(np.fft.rfft(frames, N_FFT))  # 计算每帧的幅度

# 梅尔滤波器组
nfilt = 24
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (sr / 2) / 700))  # 把 Hz 变成 Mel
mel_points = np.linspace(low_freq_mel, high_freq_mel, nfilt + 2)  # 将Mel刻度等间隔
hz_points = (700 * (10**(mel_points / 2595) - 1))  # 把 Mel 变成 Hz
bin = np.floor((N_FFT + 1) * hz_points / sr)
fbank = np.zeros((nfilt, int(np.floor(N_FFT / 2 + 1))))
for m in range(1, nfilt + 1):
    f_m_minus = int(bin[m - 1])   # left
    f_m = int(bin[m])             # center
    f_m_plus = int(bin[m + 1])    # right
    for k in range(f_m_minus, f_m):
        fbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
    for k in range(f_m, f_m_plus):
        fbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])
filter_banks = np.dot(mag_frames, fbank.T)
filter_banks = np.where(filter_banks == 0, np.finfo(float).eps, filter_banks)  # 数值稳定性

# 取对数
log_filter_banks = np.log(filter_banks)

# 离散余弦变换（DCT）- 这里使用 scipy.fftpack.dct
num_ceps = 12
mfcc = dct(log_filter_banks, type=2, axis=1, norm='ortho')[:num_ceps, :]

# 动态特征计算
delta_mfcc = librosa.feature.delta(mfcc)
delta2_mfcc = librosa.feature.delta(mfcc, order=2)
mfcc = np.concatenate((mfcc, delta_mfcc, delta2_mfcc), axis=0)

# 可视化
librosa.display.specshow(mfcc, sr=sr, x_axis='time')
plt.colorbar(format='%+2.2f')
plt.show()